
import 'dart:convert';

import 'package:freemusic/model/Lyric.dart';

import 'AbstractSong.dart';

class KugouSong extends AbstractSong {

  String songnameoriginal;

  @override
  List<AbstractSong> fromRemoteJosn(Map json) {
    final List infoList = json['data']['info'];
    List<KugouSong> result = new List();
    for(int i = 0; i < infoList.length; i++){
      KugouSong current = new KugouSong();
      current.songnameoriginal = infoList[i]['songname_original'];
      current.singerName = infoList[i]['singername'];
      current.songName = infoList[i]['songname'];
      current.hash = infoList[i]['hash'];
      current.type = infoList[i]['extname'];
      current.platform = SongPlatform.kugou;
      result.add(current);
    }
    return result;
  }

  KugouSong fromRemoteJson(String json){
    final map =  jsonDecode(json);
    if(map['err_code'] == 30020){
      this.playUrl= "";
     this.platform = "kugou";
      return this;
    }
    final Map info = map['data'];
    this.playUrl = info['play_url'];
    this.img = info['img'];
    this.timeLength = new Duration(milliseconds: info['timelength']);
    this.singerName = info['author_name'];
    this.lyrics = info['lyrics'].toString();
    this.hash = info['hash'];
    this.songName = info['song_name'];
    this.type = "mp3";
    this.platform = "kugou";
    return this;
  }

  @override
  Lyric stringToLyric() {

    Lyric lyric = Lyric();

    if (lyrics == null) {
      return lyric;
    }

    List<String> list = lyrics.split("\r\n");
    list.forEach((item) {
      if (!item.endsWith("]") && item.isNotEmpty) {
        lyric.slices.add(stringToLyricSlice(item));
      }
    });
    return lyric;
  }

  LyricSlice stringToLyricSlice(String line) {
    LyricSlice lyricSlice = LyricSlice();
    lyricSlice.slice = line.substring(10);
    int minute = int.parse(line.substring(1, 3));
    int second = int.parse(line.substring(4, 6));
    int millis = int.parse(line.substring(7, 9));

    // lyricSlice.milliseconds = minute * 60 * 1000 + second * 1000 + millis;
    lyricSlice.milliseconds = Duration(minutes: minute, seconds: second, milliseconds: millis);
    return lyricSlice;
  }

  @override
  Map toJsonMap() {
    Map map = super.toJsonMap();
    map['songnameoriginal'] = this.songnameoriginal;
    return map;
  }
  
}